package com.janj.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

//import java.io.IOException;

//自己定义的工具类
public class MyBatisUtils {
    //两个成员静态的
    private static SqlSession session = null;
    private static InputStream is = null;

    //私有构造方法
    private MyBatisUtils() {

    }

    //提供对外 Session 执行者对象
    public static SqlSession getSqlSession() {
        try {
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            session = factory.openSession(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return session;
    }

    //提供释放资源的方法
    public static void close() {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
